package com.comleader.ldmapdownload.util;

import cn.hutool.json.JSONUtil;
import com.comleader.ldmapdownload.bean.LocationEntity;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhanghang
 * @date 2020-09-26 14:42
 * @description
 */
@Component
public class ElasticsearchUtil {
    @Autowired
    private RestHighLevelClient esClient;

//    private static RestHighLevelClient client;

    /**
     * @PostContruct是spring框架的注解 spring容器初始化的时候执行该方法
     */
//    @PostConstruct
//    public void init() {
//        client = this.restHighLevelClient;
//    }
    public List<LocationEntity> searchByPhone(String num) throws IOException {


        // 设置查询索引
        SearchRequest searchRequest = new SearchRequest("es.od_xdrxl_event_*");
        // 构建查询条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        TermQueryBuilder builder = QueryBuilders.termQuery("c_usernum", num);

        boolQueryBuilder.must(builder);

        sourceBuilder.query(boolQueryBuilder);

        sourceBuilder.from(0);
        sourceBuilder.size(5000);

        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //  添加各种查询条件，进行查询
        searchRequest.source(sourceBuilder);

        SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
        List<LocationEntity> resList = new ArrayList<>();
        if(response != null){
            SearchHits hits = response.getHits();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                LocationEntity locationEntity = JSONUtil.toBean(sourceAsString, LocationEntity.class);
                // 去除脏数据（省外的或无位置信息的数据）
                if (!StringUtils.isEmpty(locationEntity.getC_uli_addr()) && locationEntity.getC_lat() != 0 && locationEntity.getC_lng() != 0){
                    resList.add(locationEntity);
                }
            }
        }

        return resList;

    }


}
